package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.entity.Result;
import com.itheima.exception.BusinessRuntimeException;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import com.itheima.utils.POIUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@RestController
@RequestMapping("/report")
@Slf4j
public class ReportController {

    @Reference
    MemberService memberService;

    @Reference
    SetmealService setmealService;

    @Reference
    ReportService reportService;


    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
        log.debug ( "运营数据统计！！" );
        Map<String, Object> result = reportService.getBussinessReport ();
        log.debug ( "result:" + result );
        return new Result ( true, MessageConst.ACTION_SUCCESS, result );
    }

    /**
     * update by 黄子兴
     *
     * @param monthRange
     * @return
     */
    @RequestMapping("/getMemberReport")
    public Result getMemberReport(@RequestBody Map<String, String> monthRange) {
        log.debug ( "getMemberReport: 获取会员统计信息: " + monthRange );
        Map<String, Object> map = memberService.getMemberReport ( monthRange );
        log.debug ( "MemberReport: " + map );
        log.debug ( "获取会员统计信息成功!!" );
        return new Result ( true, MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS, map );
    }

    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport() {
        log.debug ( "ReportController-getSetmealReport: 获取套餐统计信息" );
        List<String> setmealNames = new ArrayList<> ();//封装套餐名称集合
        List<Map> setmealCount = setmealService.getSetmealReport ();//套餐名称和预约数量集合
        if (setmealCount != null && setmealCount.size () > 0) {
            for (Map map : setmealCount) {
                String name = (String) map.get ( "name" );//套餐名称
                setmealNames.add ( name );
            }
        }
        Map<String, Object> map = new HashMap<> ();
        map.put ( "setmealNames", setmealNames );
        map.put ( "setmealCount", setmealCount );
        log.debug ( "getSetmealReport:" + map.toString () );
        return new Result ( true, MessageConst.GET_SETMEAL_COUNT_REPORT_SUCCESS, map );
    }

    /**
     * 1. 获取运营统计数据
     * 2. 创建模板对象
     * 3. 把数据写入模板中
     * 4. 下载excel到本地
     */
    @RequestMapping("/exportBusinessReport")
    public void exportBusinessReport(HttpServletResponse response) {
        try {

//1. 获取运营统计数据
            Map<String, Object> businessReportData = reportService.getBussinessReport ();
            //获取统计日期
            Object reportDate = businessReportData.get ( "reportDate" );
            Object totalMember = businessReportData.get ( "totalMember" );
            Object todayNewMember = businessReportData.get ( "todayNewMember" );
            Object thisWeekNewMember = businessReportData.get ( "thisWeekNewMember" );
            Object thisMonthNewMember = businessReportData.get ( "thisMonthNewMember" );
            Object todayOrderNumber = businessReportData.get ( "todayOrderNumber" );
            Object todayVisitsNumber = businessReportData.get ( "todayVisitsNumber" );
            Object thisWeekOrderNumber = businessReportData.get ( "thisWeekOrderNumber" );
            Object thisWeekVisitsNumber = businessReportData.get ( "thisWeekVisitsNumber" );
            Object thisMonthOrderNumber = businessReportData.get ( "thisMonthOrderNumber" );
            Object thisMonthVisitsNumber = businessReportData.get ( "thisMonthVisitsNumber" );
            List<Map<String, Object>> hotSetmeal = (List<Map<String, Object>>) businessReportData.get ( "hotSetmeal" );

            //创建模板对象
            InputStream inputStream = this.getClass ().getResourceAsStream ( "/template/report_template.xlsx" );
            XSSFWorkbook workbook = new XSSFWorkbook ( inputStream );
            //把数据写入模板中
            //获取工作表对象（sheet）
            XSSFSheet sheet = workbook.getSheet ( "Sheet1" );
            //设置统计日期
            //获取行对象
            POIUtils.writeCell ( sheet, 2, 5, reportDate );

            //设置今日新增会员数
            POIUtils.writeCell ( sheet, 4, 5, todayNewMember );

            //设置总会员数
            POIUtils.writeCell ( sheet, 4, 7, totalMember );

            //设置本周新增会员数
            POIUtils.writeCell ( sheet, 5, 5, thisWeekNewMember );

            //设置本月新增会员数
            POIUtils.writeCell ( sheet, 5, 7, thisMonthNewMember );


            //设置今日预约数
            POIUtils.writeCell ( sheet, 7, 5, todayOrderNumber );

            //设置今日到诊数
            POIUtils.writeCell ( sheet, 7, 7, todayVisitsNumber );

            //设置本周预约数
            POIUtils.writeCell ( sheet, 8, 5, thisWeekOrderNumber );

            //设置本周到诊数
            POIUtils.writeCell ( sheet, 8, 7, thisWeekVisitsNumber );

            //设置本月预约数
            POIUtils.writeCell ( sheet, 9, 5, thisMonthOrderNumber );


            //设置本月到诊数
            POIUtils.writeCell ( sheet, 9, 7, thisMonthVisitsNumber );

            //声明行号
            int rownum = 12;
            for (Map<String, Object> map : hotSetmeal) {
                POIUtils.writeCell ( sheet, rownum, 4, map.get ( "name" ) );
                POIUtils.writeCell ( sheet, rownum, 5, map.get ( "setmeal_count" ) );
                //获取占比，保留小数点后两位小数
                BigDecimal num = (BigDecimal) map.get ( "proportion" );
                String result=String.format ( "%.2f",num );
                //拼接%，按百分比的形式写出
                POIUtils.writeCell ( sheet, rownum, 6,result+"%");
                rownum++;
            }

            //下载excel到本地
            // 通过输出流进行文件下载
            ServletOutputStream out = response.getOutputStream ();
            //指定附件的格式为excel
            response.setContentType ( "application/vnd.ms-excel" );
            //attachment 以附件下载
            //下载弹出框架中的默认的文件名
            response.setHeader ( "content-Disposition", "attachment;filename=" + reportDate + "_report.xlsx" );
            //输出流下载
            workbook.write ( out );
            out.flush ();
            out.close ();
            workbook.close ();

        } catch (IOException e) {
            e.printStackTrace ();
            throw new BusinessRuntimeException ( MessageConst.GET_BUSINESS_REPORT_FAIL );
        }
    }

    /* @create by 赵晴 * @date 2020-07-07 20:52:26 */
    //按性别、按年龄查询会员信息
    @RequestMapping("/getMemberReportDivided")
    public Result getMemberReportDivided() {
        log.debug ( "按性别查询会员信息" );
        List<String> memberGenders = new ArrayList<> ();//封装会员性别集合
        List<Map> memberCountBySex = memberService.getMemberReportDivBySex ();//会员性别和数量集合
        if (memberCountBySex != null && memberCountBySex.size () > 0) {
            for (Map map : memberCountBySex) {
                String gender = (String) map.get ( "name" );//性别
                memberGenders.add ( gender );
            }
        }
        log.debug ( "按年龄段查询会员信息" );
        List<String> memberAges = new ArrayList<> ();//封装会员性别集合
        List<Map> memberCountByAge = memberService.getMemberReportDivByAge ();//会员性别和数量集合
        if (memberCountByAge != null && memberCountByAge.size () > 0) {
            for (Map map : memberCountByAge) {
                String ageGroup = (String) map.get ( "name" );//年龄段
                memberAges.add ( ageGroup );
            }
        }
        Map<String, Object> map = new HashMap<> ();
        map.put ( "memberGenders", memberGenders );
        map.put ( "memberCountBySex", memberCountBySex );
        map.put ( "memberAges", memberAges );
        map.put ( "memberCountByAge", memberCountByAge );
        log.debug ( "getMemberReportDivided:" + map.toString () );
        return new Result ( true, MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS, map );
    }
}
